<?php


namespace App\Sys\Services;

use App\Services\CommonBaseService;


class SysMenuFuncAuthService extends CommonBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'SysMenuFuncAuth:';

    protected $tokenBucket = 'Token:';

    protected $activeBucket = "Active:";

    /**
     * 后台角色授权
     * */
    public function saveMenuFuncAuth($menuFuncIds,$roleId){
        $time=nowTime();
        if(!empty($menuFuncIds)){
            //获取要保留下来的权限
            $remainedIds= $this->model
                ->where('role_id',$roleId)
                ->where('status',0)
                ->whereIn('menu_func_id',$menuFuncIds)
                ->pluck('menu_func_id')->toArray();
            $addMenuFuncIds=array_diff($menuFuncIds,$remainedIds);//获取要新增的权限
            $insertData=[];
            foreach ($addMenuFuncIds as $value){
                $insertData[]=['menu_func_id'=>$value,'role_id'=>$roleId,'create_time'=>$time,'update_time'=>$time];
            }
            //插入新增的权限
            if(!empty($insertData)){
                $this->model->insert($insertData);
            }
            //删除移除的权限
            $this->model->where('role_id',$roleId)->where('status',0)
                ->WhereNotIn('menu_func_id',$menuFuncIds)
                ->update(['status'=>2,'update_time'=>$time]);
        }else{
            $this->model->where('role_id',$roleId)->where('status',0)
                ->update(['status'=>2,'update_time'=>$time]);
        }
    }

    /**
     * 账号权限
     * */
    public function adminRoleAuth($roleId){
        $list = $this->model->alias('a')
            ->leftJoin('sys_menu_func as b','a.menu_func_id','=','b.id')
            ->where('a.role_id', '=', $roleId)
            ->where('a.status',0)
            ->selectRaw('a.menu_func_id,b.route_path')->get();
        if($list){
            $list = $list->toArray();
        }
        return $list;
    }
}
